package com.jwds.digital.bios.business.service.service.belt.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwds.digital.bios.business.core.infrastructure.dto.belt.BeltPerformanceHourReqDTO;
import com.jwds.digital.bios.business.core.infrastructure.vo.belt.BeltPerformanceHourRespVO;
import com.jwds.digital.bios.business.service.service.belt.IBeltPerformanceWeekService;
import com.jwds.digital.bios.business.core.infrastructure.dto.belt.BeltPerformanceWeekReqDTO;
import com.jwds.digital.bios.business.core.infrastructure.vo.belt.BeltPerformanceWeekRespVO;
import com.jwds.digital.bios.business.core.infrastructure.dto.belt.assembler.BeltPerformanceWeekAssembler;
import com.jwds.digital.bios.business.core.infrastructure.entity.belt.BeltPerformanceWeek;
import com.jwds.digital.bios.business.core.infrastructure.mapper.belt.BeltPerformanceWeekMapper;
import com.jwds.digital.bios.business.core.exceptions.RecordNotFoundException;
import com.jwds.tdc.framework.application.lib.page.PageRequest;
import com.jwds.tdc.framework.application.lib.page.PageResponse;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.jwds.digital.bios.business.service.service.belt.impl.BeltPerformanceHourServiceImpl.getHourRespVO;
import static com.jwds.digital.bios.business.service.service.belt.impl.BeltPerformanceHourServiceImpl.getTimeList;

/**
 * 皮带效能周表实现类
 * @author 林柏云
 * @date 2024-10-24
 */
@Slf4j
@Service
public class BeltPerformanceWeekServiceImpl extends ServiceImpl<BeltPerformanceWeekMapper, BeltPerformanceWeek> implements IBeltPerformanceWeekService {

  @Autowired
  private BeltPerformanceWeekMapper baseMapper;

  @Override
  public BeltPerformanceWeekRespVO queryById(Long id) {
    if(id == null) {
      return null;
    }
    BeltPerformanceWeek entity = baseMapper.selectById(id);
    return BeltPerformanceWeekAssembler.entity2dto(entity);
  }

  @Override
  public PageResponse<BeltPerformanceWeekRespVO> page(PageRequest<BeltPerformanceWeekReqDTO> request) {
    BeltPerformanceWeekReqDTO condition = request.getQueryCondition();
    Page<BeltPerformanceWeekRespVO> page = new Page<>(request.getPageIndex(), request.getPageSize());
    IPage<BeltPerformanceWeekRespVO> pageData = baseMapper.pageQuery(page, condition);
    return new PageResponse<>((Page<?>)pageData, pageData.getRecords());
  }

  @Override
  public List<BeltPerformanceWeekRespVO> list(BeltPerformanceWeekReqDTO reqDto) {
    return baseMapper.queryList(reqDto);
  }

  @Override
  public void add(BeltPerformanceWeekReqDTO reqDto) {
    BeltPerformanceWeek entity = BeltPerformanceWeekAssembler.dto2entity(reqDto);
    baseMapper.insert(entity);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void batchAdd(List<BeltPerformanceWeekReqDTO> dtoList) {
    dtoList.forEach(this::add);
  }

  @Override
  public void update(BeltPerformanceWeekReqDTO reqDto) {
    BeltPerformanceWeek oldEntity = baseMapper.selectById(reqDto.getId());
    if (oldEntity == null) {
      throw new RecordNotFoundException();
    }
    BeltPerformanceWeek newEntity = BeltPerformanceWeekAssembler.dto2entity(reqDto, oldEntity);
    baseMapper.updateById(newEntity);
  }

  @Override
  public void delete(Long id) {
    BeltPerformanceWeek oldEntity = baseMapper.selectById(id);
    if (oldEntity == null) {
      throw new RecordNotFoundException();
    }
    baseMapper.deleteById(id);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void batchDelete(List<Long> ids) {
    for (Long id : ids) {
      delete(id);
    }
  }

  @Override
  public BeltPerformanceHourRespVO analyze(BeltPerformanceHourReqDTO reqDto) {
    // 取开始和结束时间，保留小时及以上单位时间
    //    reqDto.setStartTime(reqDto.getStartTime().withMinute(0).withSecond(0).withNano(0));
    //    reqDto.setEndTime(reqDto.getEndTime().withMinute(0).withSecond(0).withNano(0));
    reqDto.setEndTime(LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0));
    reqDto.setStartTime(reqDto.getEndTime().minusDays(7));
    // 获取上周开始时间（周一 00:00:00）
    LocalDateTime startOfWeek = reqDto.getStartTime()
            .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
            .withHour(0).withMinute(0).withSecond(0).withNano(0);
    // 获取本周结束时间（周日 23:59:59）
    LocalDateTime endOfWeek = reqDto.getEndTime()
            .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY))
            .withHour(23).withMinute(59).withSecond(59).withNano(0);
    BeltPerformanceHourRespVO beltPerformanceHourRespVO = baseMapper.analyze(reqDto.getId(), startOfWeek, endOfWeek);
    List<LocalDateTime> timeList = getTimeList(reqDto.getStartTime().minusDays(7*7), reqDto.getEndTime(), ChronoUnit.WEEKS);
    // 每个时间段的负载率和空载负载率
    return  getHourRespVO(reqDto, timeList, beltPerformanceHourRespVO,baseMapper,ChronoUnit.WEEKS);
  }

}